package gsp420;

public class LinkedList<T>
{
	public class Node
	{
		T data;
		Node next;
		Node(T data)
		{
			this.data = data;
		}
	}
	
	/** the first element of a list */
	Node head;
	
	/** @return the first element in the list, which is also removed from the list */
	T pop()
	{
		if(head == null)return null;
		T data = head.data;
		head = head.next;
		return data;
	}
	
	/** @return the last node in the list, or null if no nodes are in the list */
	Node getLast()
	{
		Node cursor = head;
		while(cursor != null && cursor.next != null)
		{
			cursor = cursor.next;
		}
		return cursor;
	}
	
	/** adds the given element to the back of the list */
	void pushBack(T data)
	{
		Node newNode = new Node(data);
		Node n = getLast();
		if(n != null)
			n.next = newNode;
		else
			head = newNode;
	}
	
	/** @return number of elements in the Linked List */
	int length()
	{
		Node cursor = head;
		int count = 0;
		while(cursor != null)
		{
			cursor = cursor.next;
			count++;
		}
		return count;
	}

	/** @return data at the given element, where 0 is the head eelment */
	T getData(int i)
	{
		Node cursor = head;
		int count = 0;
		while(count < i)
		{
			cursor = cursor.next;
			count++;
		}
		return cursor.data;
	}
	
	public static void main(String[] args)
	{
		LinkedList<Integer> list = new LinkedList<Integer>();
		list.pushBack(1);
		list.pushBack(3);
		list.pushBack(5);
		list.pushBack(9);
		list.pushBack(11);
		System.out.print("{");
		for(int i = 0; i < list.length(); ++i)
		{
			if(i > 0)System.out.print(", ");
			System.out.print(list.getData(i));
		}
		System.out.println("}");		
	}
}
